//
//  ViewController.m
//  PDFMerge
//
//  Created by wangyx on 2021/12/17.
//

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (NSString *)joinPDF:(NSArray <NSURL *>*)listOfPaths {
    
    NSURL *pdfPathOutput = [[listOfPaths.firstObject URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"all.pdf"];
    CFURLRef pdfURLOutput = (CFURLRef)CFBridgingRetain(pdfPathOutput);
    
    NSInteger numberOfPages = 0;
    // Create the output context
    CGContextRef writeContext = CGPDFContextCreateWithURL(pdfURLOutput, NULL, NULL);
    
    for (NSString *source in listOfPaths) {
        CFURLRef pdfURL = (CFURLRef)CFBridgingRetain(source);
        
        //file ref
        CGPDFDocumentRef pdfRef = CGPDFDocumentCreateWithURL((CFURLRef) pdfURL);
        numberOfPages = CGPDFDocumentGetNumberOfPages(pdfRef);
        
        // Loop variables
        CGPDFPageRef page;
        CGRect mediaBox;
        
        // Read the first PDF and generate the output pages
        for (int i=1; i<=numberOfPages; i++) {
            page = CGPDFDocumentGetPage(pdfRef, i);
            mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
            CGContextBeginPage(writeContext, &mediaBox);
            CGContextDrawPDFPage(writeContext, page);
            CGContextEndPage(writeContext);
        }
        
        CGPDFDocumentRelease(pdfRef);
        CFRelease(pdfURL);
    }
    CFRelease(pdfURLOutput);
    
    // Finalize the output file
    CGPDFContextClose(writeContext);
    CGContextRelease(writeContext);
    
    return pdfPathOutput.path;
}


- (IBAction)onSelectFileClick:(id)sender {
    NSOpenPanel *open = [NSOpenPanel openPanel];
    [open setAllowsMultipleSelection:YES];
    [open setTitle:@"Use ⌘ To  Multi-select"];
    [open setPrompt:@"Start"];
    [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
    NSInteger openPanelClicked = [open runModal];
    NSArray *urls;
    if (openPanelClicked == NSModalResponseOK) {
        urls = [open URLs];
        [self joinPDF:urls];
    }
}

@end
